package com.qf.aspect;


import com.qf.TryException.AppException;
import com.qf.TryException.TryException;
import com.qf.anno.Retry;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;


/**
 * @author sky
 * @date 2022-08-20
 */
@Aspect
@Component
@Order(Integer.MIN_VALUE)
public class MyAspect {

    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    @Around("@annotation(com.qf.anno.Retry)")
    public Object UpdateNum(ProceedingJoinPoint point) throws Throwable {
        System.out.println("retry..................................");
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String methodName = point.getSignature().getName();
        Class clazz = point.getTarget().getClass();
        Method method = clazz.getDeclaredMethod(methodName,methodSignature.getParameterTypes());
        Retry retry = method.getDeclaredAnnotation(Retry.class);
        int i = retry.retryTime();
        int max = retry.maxRetryCount();
        System.out.println("max:"+max);
        for (int j = 1; j<max; j++){
            System.out.println("aaaa:"+j);
            try {
                Thread.sleep(i);
                Object proceed = point.proceed();
                System.out.println("=====================================================");
                return proceed;
            }catch (Exception e){
                if (e.getClass() != retry.Exceptionclass()){
                    throw e;
                }else{
                    if (i <= retry.maxTime()){
                        i *= retry.mutiple();
                    }

                }
            }
        }

        throw new AppException("500","购买失败");
    }
}
